"""
工作流模板 API Schema
"""
from pydantic import BaseModel, Field, field_validator
from typing import Optional, List, Dict, Any
from datetime import datetime


# ============ 工作流节点定义 Schema（重用） ============

class WorkflowNode(BaseModel):
    """工作流节点定义"""
    id: str = Field(..., description="节点ID")
    type: str = Field(..., description="节点类型")
    name: str = Field(..., description="节点名称")
    config: Dict[str, Any] = Field(default_factory=dict, description="节点配置")
    next: Optional[str] = Field(None, description="下一个节点ID")


class WorkflowDefinition(BaseModel):
    """工作流定义"""
    nodes: List[WorkflowNode] = Field(..., description="节点列表")


# ============ 工作流模板 CRUD Schema ============

class WorkflowTemplateCreate(BaseModel):
    """创建工作流模板请求"""
    name: str = Field(..., description="模板名称", min_length=1, max_length=255)
    description: Optional[str] = Field(None, description="模板描述")
    workflow_definition: WorkflowDefinition = Field(..., description="工作流定义")
    created_by: Optional[str] = Field(None, description="创建人")

    @field_validator('name')
    @classmethod
    def name_must_not_be_empty(cls, v: str) -> str:
        if not v.strip():
            raise ValueError('模板名称不能为空')
        return v.strip()


class WorkflowTemplateUpdate(BaseModel):
    """更新工作流模板请求（创建新版本）"""
    name: Optional[str] = Field(None, description="新名称", min_length=1, max_length=255)
    description: Optional[str] = Field(None, description="新描述")
    workflow_definition: Optional[WorkflowDefinition] = Field(None, description="新工作流定义")
    status: Optional[str] = Field(None, description="模板状态（草稿/已发布/已归档）")
    change_log: Optional[str] = Field(None, description="变更日志")


class WorkflowTemplateResponse(BaseModel):
    """工作流模板响应（列表项）"""
    id: int
    name: str
    description: Optional[str] = None
    version: int
    status: str
    created_at: datetime
    updated_at: datetime
    created_by: Optional[str] = None

    model_config = {"from_attributes": True}


class WorkflowTemplateDetailResponse(BaseModel):
    """工作流模板详情响应"""
    id: int
    name: str
    description: Optional[str] = None
    workflow_definition: Dict[str, Any]
    version: int
    parent_version_id: Optional[int] = None
    change_log: Optional[str] = None
    status: str
    created_at: datetime
    updated_at: datetime
    created_by: Optional[str] = None

    model_config = {"from_attributes": True}


class WorkflowTemplateListResponse(BaseModel):
    """工作流模板列表响应"""
    total: int
    page: int
    page_size: int
    items: List[WorkflowTemplateResponse]


# ============ 版本管理 Schema ============

class VersionInfo(BaseModel):
    """版本信息"""
    id: int
    version: int
    created_at: datetime
    updated_at: datetime
    parent_version_id: Optional[int] = None
    change_log: Optional[str] = None
    created_by: Optional[str] = None


class VersionHistoryResponse(BaseModel):
    """版本历史响应"""
    versions: List[VersionInfo]


class VersionDiffResponse(BaseModel):
    """版本对比响应"""
    version1: Dict[str, Any]
    version2: Dict[str, Any]


class RollbackRequest(BaseModel):
    """回滚请求"""
    target_version: int = Field(..., description="目标版本号", ge=1)


# ============ 从实例创建模板 Schema ============

class CreateTemplateFromInstanceRequest(BaseModel):
    """从实例创建模板请求"""
    template_name: str = Field(..., description="新模板名称", min_length=1, max_length=255)
    description: Optional[str] = Field(None, description="模板描述")
    created_by: Optional[str] = Field(None, description="创建人")

    @field_validator('template_name')
    @classmethod
    def template_name_must_not_be_empty(cls, v: str) -> str:
        if not v.strip():
            raise ValueError('模板名称不能为空')
        return v.strip()
